<template>
  <el-dialog
    v-model="visible"
    title="导出资产详情"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form :model="formData" label-width="120px">
      <el-form-item label="导出格式">
        <el-radio-group v-model="formData.export_format">
          <el-radio label="xlsx">Excel (xlsx)</el-radio>
          <el-radio label="csv">CSV</el-radio>
          <el-radio label="json">JSON</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="包含详细信息">
        <el-switch v-model="formData.include_details" />
        <div class="form-tip">开启后将包含完整的资产详情信息</div>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button
        type="primary"
        :loading="exporting"
        @click="handleExport"
        :disabled="!assetId"
      >
        开始导出
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { exportPanAssetDetail, downloadPanAssetExport } from "../../../servers";

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  assetId: { type: Number, default: null },
});

const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "success"): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value),
});

const exporting = ref(false);
const formData = ref({
  export_format: "xlsx" as "xlsx" | "csv" | "json",
  include_details: true,
});

// 监听弹窗打开，重置表单
watch(visible, (newVal) => {
  if (newVal) {
    formData.value = {
      export_format: "xlsx",
      include_details: true,
    };
  }
});

// 导出
const handleExport = async () => {
  if (!props.assetId) {
    ElMessage.warning("资产ID不存在");
    return;
  }

  exporting.value = true;
  try {
    const result = await exportPanAssetDetail(props.assetId, {
      export_format: formData.value.export_format,
      include_details: formData.value.include_details,
    });

    if (result.code === 200 && result.data) {
      const { export_id, download_url, expires_at } = result.data;

      // 如果有下载URL，直接下载
      if (download_url) {
        // 使用完整的 URL 路径
        const fullUrl = download_url.startsWith("http")
          ? download_url
          : `${window.location.origin}${download_url}`;

        const link = document.createElement("a");
        link.href = fullUrl;
        link.download = `资产详情_${props.assetId}_${new Date()
          .toISOString()
          .slice(0, 10)
          .replace(/-/g, "")}.${formData.value.export_format}`;
        link.style.visibility = "hidden";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        ElMessage.success("导出成功，文件已开始下载");
        emit("success");
        visible.value = false;
      } else if (export_id) {
        // 如果有导出ID，轮询下载状态
        ElMessage.success("导出任务已创建，正在处理中...");
        await pollExportStatus(export_id);
        emit("success");
        visible.value = false;
      } else {
        ElMessage.success("导出成功");
        emit("success");
        visible.value = false;
      }
    } else {
      ElMessage.error(result.message || "导出失败");
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "导出失败");
  } finally {
    exporting.value = false;
  }
};

// 轮询导出状态
const pollExportStatus = async (exportId: string): Promise<void> => {
  const maxAttempts = 30; // 最多轮询30次
  const interval = 2000; // 每2秒轮询一次
  let attempts = 0;

  const poll = async (): Promise<void> => {
    try {
      const blob = await downloadPanAssetExport(exportId);
      // 如果返回的是 Blob，说明下载成功
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `资产详情_${props.assetId}_${new Date()
        .toISOString()
        .slice(0, 10)
        .replace(/-/g, "")}.${formData.value.export_format}`;
      link.style.visibility = "hidden";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);

      ElMessage.success("导出完成，文件已开始下载");
    } catch (error: any) {
      if (error?.response?.status === 202) {
        // 还在处理中
        attempts++;
        if (attempts < maxAttempts) {
          setTimeout(() => poll(), interval);
        } else {
          ElMessage.warning("导出超时，请稍后手动下载");
        }
      } else {
        ElMessage.error(error?.message || "导出失败");
      }
    }
  };

  await poll();
};

// 取消
const handleCancel = () => {
  visible.value = false;
};
</script>

<style scoped lang="scss">
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
